var express = require('express');
var router = express.Router();

const sql = require("../sql/sql");
const order = require("../sql/order");
const cart = require("../sql/cart");
const tools = require("../tools/index");
const uuid = require("node-uuid");
const payTools = require('../tools/tools');
const config = require('../config/index');
const axios = require('axios');
const qrcode = require('qrcode');

function createNum (){
    return Date.now() + "" + parseInt(Math.random() * 10000)
}

/**
* @apiGroup 订单模块
* @api {get} /order/wxPay 微信支付
* @apiVersion 0.0.0
* @apiDescription 微信支付
* @apiParam {String} body 收账描述
* @apiParam {object} out_trade_no 订单号
* @apiParam {object} total_fee 价钱/单位：分
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccessExample {json} Success-Response:
res.send({
    state:200,
    title:"生成二维码",
    data
})
* @apiSampleRequest http://localhost:3000/api/order/wxPay
*/

router.get('/wxPay',function(req,res,next){
    let { body, out_trade_no, total_fee } = req.query;

    const mch_id = config.mch_id;
    const appid = config.appid;
    const notify_url = config.notify_url;
    const nonce_str = payTools.randomString();
    const trade_type = "NATIVE";

    const M = {
        appid, mch_id, nonce_str, notify_url, trade_type, body, out_trade_no, total_fee
    }

    const sign = payTools.getSign(M);

    const data = payTools.getXml(M,sign);

    axios.post(config.unifiedorder,data).then(response=>{
        let obj = payTools.xml2js(response.data);

        let code = obj.xml.code_url.value;

        qrcode.toDataURL(code, (err,data) => {
            res.send({
                state:200,
                title:"生成二维码",
                data
            })
        })
    })
})

/**
* @apiGroup 订单模块
* @api {post} /order/add 添加订单
* @apiVersion 0.0.0
* @apiDescription 添加订单
* @apiParam {String} userId 用户的唯一Id
* @apiParam {object} proData 要存的商品信息
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccessExample {json} Success-Response:
res.send({
    stete:200,
    title:"添加订单成功"
})
res.send({
    state:300,
    title:"登录信息已失效"
})
* @apiSampleRequest http://localhost:3000/api/order/add
*/


router.post('/add',function(req,res,next){
    const { userId, proData } = req.body;
    tools.verify(req).then(()=>{
        sql.insert(order,{
            userId,
            orderId:createNum(),
            time:Date.now(),
            proData,
            state:0
        }).then(()=>{
            sql.find(cart,{userId}).then(data=>{
                let arr = data[0].cartData;
                arr = arr.filter(val=>{
                    return !val.flag
                })
                sql.update(cart,{userId},{cartData:arr}).then(()=>{
                    res.send({
                        stete:200,
                        title:"添加订单成功"
                    })
                })
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录信息已失效"
        })
    })
})

router.post('/payNow', function(req, res, next) {
    const { userId, proData } = req.body;
    tools.verify(req).then(()=>{
    sql.insert(order, {
            userId,
            orderId:createNum(),
            time: Date.now(),
            proData,
            state: 1
        }).then(() => {
            res.send({
                stete: 200,
                title: "购买成功"
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录信息已失效"
        })
    })
})

/**
* @apiGroup 订单模块
* @api {get} /order 获取订单信息
* @apiVersion 0.0.0
* @apiDescription 获取订单信息
* @apiParam {String} userId 用户的唯一Id
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {json} data 请求说明
* @apiSuccessExample {json} Success-Response:
res.send({
    stete:200,
    title:"请求订单数据成功",
    data:[{},{}]
})
res.send({
    state:300,
    title:"登录信息已失效"
})
* @apiSampleRequest http://localhost:3000/api/order
*/

router.get('/',function(req,res,next){
    const { userId } = req.query;
    tools.verify(req).then(()=>{
        sql.find(order,{userId},{_id:0,__v:0}).then(data=>{
            res.send({
                state:200,
                title:"请求订单数据成功",
                data
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录信息已失效"
        })
    })
})

/**
* @apiGroup 订单模块
* @api {post} /order/pay 付款
* @apiVersion 0.0.0
* @apiDescription 付款
* @apiParam {object} orderId 订单唯一Id
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccessExample {json} Success-Response:
res.send({
    state:200,
    title:"付款成功"
})
res.send({
    state:300,
    title:"登录信息已失效"
})
* @apiSampleRequest http://localhost:3000/api/order/pay
*/

router.post('/pay',function(req,res,next){
    const { orderId } = req.body;
    tools.verify(req).then(()=>{
        sql.update(order,{orderId},{state:2}).then(()=>{
            res.send({
                state:200,
                title:"付款成功"
            })
        })
    }).catch(err=>{
        res.send({
            stete:300,
            title:"登录信息已失效"
        })
    })
})

/**
* @apiGroup 订单模块
* @api {post} /order/del 删除订单
* @apiVersion 0.0.0
* @apiDescription 删除订单
* @apiParam {object} orderId 订单唯一Id
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccessExample {json} Success-Response:
res.send({
    stete:200,
    title:"删除成功",
    data:data[0]
})
res.send({
    state:300,
    title:"登录信息已失效"
})
* @apiSampleRequest http://localhost:3000/api/order/del
*/

router.post('/del',function(req,res,next){
    const { orderId } = req.body;
    tools.verify(req).then(()=>{
        sql.delete(order,{orderId}).then(()=>{
            res.send({
                state:200,
                title:"删除成功"
            })
        })
    }).catch(err=>{
        res.send({
            stete:300,
            title:"登录信息已失效"
        })
    })
})

/**
* @apiGroup 订单模块
* @api {get} /order/orderDetail 订单详情
* @apiVersion 0.0.0
* @apiDescription 订单详情
* @apiParam {String} userId 用户的唯一Id
* @apiParam {object} orderId 订单唯一Id
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccessExample {json} Success-Response:
res.send({
    stete:200,
    title:"获取订单详情成功",
    data:data[0]
})
res.send({
    state:300,
    title:"登录信息已失效"
})
* @apiSampleRequest http://localhost:3000/api/order/orderDetail
*/

router.get("/orderDetail",function(req,res,next){
    const { userId,orderId } = req.query;
    tools.verify(req).then(()=>{
        sql.find(order,{userId,orderId},{_id:0,__v:0}).then((data)=>{
            res.send({
                stete:200,
                title:"获取订单详情成功",
                data:data[0]
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录信息已失效"
        })
    })
})

/**
* @apiGroup 订单模块
* @api {post} /order/del 删除订单
* @apiVersion 0.0.0
* @apiDescription 删除订单
* @apiParam {object} orderId 订单唯一Id
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccessExample {json} Success-Response:
res.send({
    state:200,
    title:"删除成功"
})
res.send({
    state:300,
    title:"登录信息已失效"
})
* @apiSampleRequest http://localhost:3000/api/order/del
*/

router.post('/del',function(req,res,next){
    const { orderId } = req.body;
    tools.verify(req).then(()=>{
        sql.delete(order,{orderId}).then(()=>{
            res.send({
                state:200,
                title:"删除成功"
            })
        })
    }).catch(err=>{
        res.send({
            stete:300,
            title:"登录信息已失效"
        })
    })
})

module.exports = router;
